<template>
    <view class="globe_back">
        <view class="box">
            <u-picker :show="show" :columns="columns" keyName="title" @confirm="confirm" @cancel="cancel"></u-picker>
            <view class="flex justify_content_between back_fff model" @click="show = true">
                <view class="carbox1 inpu flex">
                    <view class="carmodel">开锁类型</view>
                    <input style="font-size: 28rpx" disabled placeholder="请选择开锁类型" v-model="lockMode.title" />
                </view>
                <view>
                    <image class="icon_r" src="https://jiuyuan.smomotbo.com/static/imgs/query-info/next-icon.png"
                        mode="widthFix"></image>
                </view>
            </view>
            <!-- 现场照片 -->
            <view class="imgbox">
                <text class="manageLabel mt-20 mr-10">现场照片</text>
                <view style="padding-top: 10rpx;">
                    <!-- <view class="xcimg" v-if="formData.images.length > 0" v-for="(item, i) in formData.images">
                        <image class="storeImg" :src="$lz.cdn(item, 3)" mode="center"
                            style="width: 140rpx; height: 140rpx; display: inline-block"></image>
                        <view class="imm_delete" @click="deletephotos(i)">
                            <image class="icon_ljt" :src="url + 'icon_sc.png'"></image>
                        </view>
                    </view>
                    <view class="img_add" style="display: inline-block" v-if="formData.images.length < maxImagesNum"
                        @click="instoreImages">
                        <image :src="url + 'updata-img.png'" mode="widthFix" style="width: 100%; height: 100%"></image>
                    </view> -->
					<u-upload
						:fileList="fileList6"
						@afterRead="afterRead"
						@delete="deletePic"
						name="6"
						multiple
						:maxCount="6"
						width="70"
						height="70"
						>
						<view class="img_add" style="display: inline-block" v-if="formData.images.length < maxImagesNum" >
						    <image :src="url + 'updata-img.png'" mode="widthFix" style="width: 100%; height: 100%"></image>
						</view>
					</u-upload>
                </view>
            </view>
            <view class="model back_fff">
                <!-- 定位服务 -->
                <view class="flex justify_content_between">
                    <view class="flex carbox">
                        <view class="carmodel">定位服务</view>
                        <view class="flex justify_content_between line_F7FAFF from-title-box align_items_center"
                            style="width: 80%" @click="chooseCurrentLocation">
                            <input class="f_28 cl_00091A pb_16" disabled placeholder-class="cl_CCCED1"
                                v-model="user_location" type="text" value="" placeholder="请选择开锁定位服务" />
                            <image class="img_32" src="https://jiuyuan.smomotbo.com/static/imgs/me-report/posi-icon.png"
                                mode="widthFix"></image>
                        </view>
                    </view>
                </view>
                <!-- 姓名 -->
                <view class="flex namebox carbox">
                    <text class="nametitle">姓名</text>
                    <view class="inpu line_F7FAFF">
                        <input v-model="formData.name" class="name" type="text" placeholder="请填写您的姓名" />
                    </view>
                </view>
                <!-- 联系电话 -->
                <view class="flex namebox carbox">
                    <text class="nametitle">联系电话</text>
                    <view class="inpu line_F7FAFF">
                        <input v-model="formData.mobile" class="name" type="text" placeholder="请填写您的联系电话" />
                    </view>
                </view>
                <!-- 预算报价 -->
                <!-- <view class="flex namebox carbox">
                    <text class="nametitle">预算报价</text>
                    <view class="inpu line_F7FAFF">
                        <input v-model="formData.budget_money" class="name" type="text" :placeholder="placeholders" />
                    </view>
                    <text>元</text>
                </view> -->
            </view>
            <!-- <view class="tip">请确认信息准确性，预算报价不得低于￥{{unitPrice}}</view> -->
        </view>
        <!-- 底部 -->
        <view class="button flex justify_content_between">
            <view class="TotalPrice">
                <view class="f_24">
                    费用：
                    <text style="color: #ff6401; font-size: 32rpx; font-weight: bold">{{ $lz.money(formData.budget_money)
                    }}</text>
                </view>
            </view>
            <view class="buy" @click="tj">立即下单</view>
        </view>
    </view>
</template>

<script>
import { common } from '@/common/serve.js';
import { getConfByCode, upload, getDictByCode, unifyOrder, getDirectionByDriving } from '@/api';

export default {
    data() {
        return {
            url: '',
            maxImagesNum: 4,
            show: false,
            lockMode: {},
            formData: {
                location: { address: '', fullAddress: '', latitude: '', longitude: '', name: '' },
                type: 0,
                images: [],
                name: '',
                mobile: '',
                budget_money: 0
            },
            columns: [],
			trailer_address:'',
			trailer_longitude:'',
			trailer_latitude:'',
			user_location:'',
			user_longitude:'',
			user_latitude:'',
			title:'',
			images:[],
			fileList6: [],
			unitPrice:0,
			placeholders:'',
			k:0,
			lat:'',
			lng:'',
        };
    },
    onShow() {
		var that= this
		uni.getLocation({
			type: 'wgs84',
			success: function (res) {
				that.lat=res.latitude;
				that.lng=res.longitude;
			}
		});
        this.url = this.baseUrl + this.imgPath;
        this.getLockMode();
    },
    methods: {
		// 拖车下单
		tj() {
			if(!this.lockMode.title){
				this.$.ti_shi('请选择开锁类型');
				return;
			}
			if(!this.images.join(',')){
				this.$.ti_shi('请上传现场图片');
				return;
			}
			if(!this.user_location){
				this.$.ti_shi('请选择开锁位置');
				return;
			}
			if(!this.formData.name){
				this.$.ti_shi('请填写姓名');
				return;
			}
			if(!this.formData.mobile){
				this.$.ti_shi('请填写联系电话');
				return;
			}
			if(!this.formData.mobile){
				this.$.ti_shi('请填写联系电话');
				return;
			}
			if(this.formData.budget_money<this.unitPrice){
				let msg='预算报价不得低于'+this.unitPrice+'元';
				this.$.ti_shi(msg);
				return;
			}
			
			
		  this.$.ajax(1,"POST","index/unlock_and_place_an_order",{
				unlock_type:this.lockMode.title,	
				on_site_photos:this.images.join(','),	
				// trailer_address:this.trailer_address,	
				// trailer_longitude:this.trailer_longitude,	
				// trailer_latitude:this.trailer_latitude,	
				user_location:this.user_location,	
				user_longitude:this.user_longitude,	
				user_latitude:this.user_latitude,	
				consignee:this.formData.name,	
				mobile:this.formData.mobile,
				actual_price:this.formData.budget_money,
				t_km:this.k,
		  },(res)=>{
				if(res.code==200){
				     var that =this
				      uni.requestPayment({
				      	provider: "weixin",
				      	timeStamp: res.data.timeStamp,
				      	nonceStr: res.data.nonceStr,
				      	package: res.data.package,
				      	signType: res.data.signType,
				      	paySign: res.data.paySign,
				      	success: function (ress) {
				      		setTimeout(() => {
				      			uni.navigateBack({
				      				delta:1
				      			})
				      		}, 1000);
				      	},
				      	fail: function (err) {
				      		console.log(err)
				      		that.$.ti_shi(err)
				      					
				      	}
				      });
				}else{
				   this.$.ti_shi(res.msg);
				}
		  })
		},
        getLockMode() {
            // getDictByCode('lock_mode').then((res) => {
            //     this.columns = [res.data];
            // });
			this.$.ajax(1,"POST","index/unlocktype",{},(res)=>{
			  if(res.code==200){
				 this.unitPrice = res.unitPrice;
				 this.columns = [res.data];
				 this.placeholders="请填写您的预算报价,不能低于￥"+res.unitPrice
				 
			  }else{
			     this.$.ti_shi(res.msg);
			  }
			})
        },
        // 删除现场照片
        deletephotos(i) {
            this.formData.images.splice(i, 1);
        },
        // 现场照片
        async instoreImages() {
            const images = this.formData.images;
            const count = this.maxImagesNum - images.length; //图片长度
            this.$lz.chooseImage({ count: count }, async (res) => {
                const result = await res.map(async ({ path }) => {
                    const {
                        data: {
                            data: { hash }
                        }
                    } = await upload(path);
                    return hash;
                });
                const results = await Promise.all(result);
                this.formData.images = this.$lz.union(images, results);
            });
        },
        chooseCurrentLocation() {
            this.$.choose_address((res) => {
            	this.user_location=res.address
            	this.user_longitude=res.lng
            	this.user_latitude=res.lat
				let k=this.$.calculateDistance(this.lat,this.lng,res.lat,res.lng).toFixed(2)
				// console.log(this.lat,this.lng,res.lat,res.lng,k)
				this.k=Number(k)
            });
        },
        buy() {
            unifyOrder(5, { meta: this.formData }).then(({ data: { id } }) => {
                // this.$u.route('/pages/index/payment', { id })
            });
        },
        confirm(e) {
            const item = e.value[0];
            this.lockMode = item;
            this.formData.type = item.key;
			this.formData.budget_money=item.money
            this.show = false;
        },
        cancel() {
            this.show = false;
        },
		// 删除图片
		deletePic(event) {
			this.images.splice(event.index, 1)
			this[`fileList${event.name}`].splice(event.index, 1)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList${event.name}`].length
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				let item = this[`fileList${event.name}`][fileListLen]
				this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: result
				}))
				fileListLen++
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.$.ajax_url+'common/upload', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: (res) => {
						this.images.push(JSON.parse(res.data).data.url)
						 // console.log()
						setTimeout(() => {
							resolve(res.data.data)
						}, 1000)
					}
				});
			})
		},
    }
};
</script>

<style scoped lang="scss">
.xcimg {
    width: 140rpx;
    height: 140rpx;
    display: inline-block;
    position: relative;
    margin: 10rpx 9rpx 0;

    .imm_delete {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.6);
        text-align: center;
        line-height: 140rpx;

        .icon_ljt {
            width: 40rpx;
            height: 40rpx;
        }
    }
}

.box {
    padding: 32rpx;

    .icon_r {
        width: 32rpx;
        height: 32rpx;
        vertical-align: middle;
    }

    .model {
        padding: 32rpx 24rpx;
        border-radius: 24rpx;
        margin-top: 24rpx;
    }

    .carbox {
        width: 100%;
        padding: 24rpx 0;
    }

    .carbox1 {
        width: 100%;
    }

    .inpu {
        width: 70%;
        padding-bottom: 16rpx;
    }

    .carmodel,
    .title {
        width: 30%;
        color: #333a47;
        font-size: 28rpx;
        display: inline-block;
    }

    .car {
        width: 60%;
        font-size: 28rpx;
        display: inline-block;
    }

    .img_add {
        width: 140rpx;
        height: 140rpx;
        display: inline-block;
        margin-left: 5rpx;
        // margin-top: 15rpx;
    }

    .imgbox {
        background: white;
        border-radius: 24rpx;
        padding: 32rpx 24rpx;
        color: #333a47;
        font-size: 28rpx;
        margin-top: 24rpx;
    }

    .manageLabel {
        width: 30%;
    }

    .nametitle {
        width: 27%;
        font-size: 28rpx;
    }

    .name {
        font-size: 28rpx;
    }

    .tip {
        color: #3377ff;
        font-size: 24rpx;
        margin-top: 24rpx;
    }
}

.button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 16rpx 32rpx 50rpx;
    background: #ffffff;

    .buy {
        width: 176rpx;
        height: 76rpx;
        line-height: 76rpx;
        text-align: center;
        color: white;
        border-radius: 8rpx;
        background-image: linear-gradient(to right, #ff924d, #ff6401);
    }
}
</style>
